package com.cryptape.cita_wallet;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.CrashUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.Utils;
import com.cryptape.cita_wallet.bean.CurrencyPrice;
import com.cryptape.cita_wallet.language.MultiLanguageUtil;
import com.cryptape.cita_wallet.net.common.BaseUrlUtils;
import com.cryptape.cita_wallet.net.common.NetWorkManager;
import com.cryptape.cita_wallet.net.common.RxSubscriber;
import com.cryptape.cita_wallet.net.common.RxSubscriber2;
import com.cryptape.cita_wallet.net.response.BaseResponse;
import com.cryptape.cita_wallet.service.http.EthRpcService;
import com.cryptape.cita_wallet.service.http.TokenService;
import com.cryptape.cita_wallet.util.crypto.AESCrypt;
import com.cryptape.cita_wallet.util.crypto.WalletEntity;
import com.cryptape.cita_wallet.util.db.SharePrefUtil;
import com.github.anrwatchdog.ANRError;
import com.github.anrwatchdog.ANRWatchDog;
import com.mangoworld.android.BuildConfig;
import com.mangoworld.android.R;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tencent.bugly.crashreport.CrashReport;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.android.schedulers.AndroidSchedulers;
import rx.Subscriber;

/**
 * Created by duanyytop on 2018/4/17
 */
public class CytonApplication extends Application {
    private final String mFilePath = "/MangoWorld/Crash";
    private static CytonApplication instance = null;

    public static CytonApplication getInstance() {
        return instance;
    }

    public String MIDCode;
    public boolean midQuerySuccess;
    public String MGPPrice;
    public String registrationid;
    public int VStimulate = 0;

    //static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    @Override
    public void onCreate() {
        super.onCreate();
//        LanguageKeeper.getInstance().init(this);
        instance = this;
        Context context = getApplicationContext();
        // 获取当前包名
        String packageName = context.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
// 初始化Bugly
        CrashReport.initCrashReport(context, "3e29e515b3", BuildConfig.IS_DEBUG, strategy);
// 如果通过“AndroidManifest.xml”来配置APP信息，初始化方法如下
// CrashReport.initCrashReport(context, strategy);
//        CrashReport.initCrashReport(getApplicationContext(), "3e29e515b3", false);
        //初始化工具库
        Utils.init(this);
        LogUtils.dTag("CrashUtils==", "CrashUtils = " + getSDPath().getAbsolutePath());
        CrashUtils.init(getSDPath());
        MultiLanguageUtil.init(this);
        ZXingLibrary.initDisplayOpinion(this);
        WalletEntity.initWalletMnemonic(this);
        SharePrefUtil.init(this);
        EthRpcService.init(this);
        AESCrypt.init(this);

        NetWorkManager.getInstance().init();
        NetWorkManager.getRequest().queryCurrency(BaseUrlUtils.PRICE_MGP)
                .observeOn(io.reactivex.android.schedulers.AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<BaseResponse<CurrencyPrice>>() {
                    @Override
                    public void onFail(String failMsg) {

                    }

                    @Override
                    public void onSuccess(BaseResponse data) {
                        try {
                            if (data.isSuccess()) {
                                CytonApplication.getInstance().MGPPrice = ((CurrencyPrice) data.getData()).getPrice().toPlainString();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });

        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        registrationid = JPushInterface.getRegistrationID(this);
        SharePrefUtil.putRegistrationID(registrationid);
        Log.e("CytonApplication", "registrationid:" + registrationid);
//        new LanguageKeeper(this).initLocalLanguage();
        registerActivityLifecycle();
    }

    /**
     * 获取sd卡路径
     *
     * @return
     */
    private File getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            // 这里可以修改为你的路径
            sdDir = new File(Environment.getExternalStorageDirectory() + mFilePath);
            if (!sdDir.exists()) {
                sdDir.mkdirs();
            }
        }
        return sdDir;
    }

    private void setupANRWatchdog() {
        // Report only main thread due to way too big report - https://github.com/SalomonBrys/ANR-WatchDog/issues/29
        new ANRWatchDog(2000)
                .setReportMainThreadOnly()
                .setANRListener(new ANRWatchDog.ANRListener() {
                    @Override
                    public void onAppNotResponding(ANRError error) {
                        Log.e("ANR", error.fillInStackTrace().getMessage());
                    }
                }).start();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        MultiLanguageUtil.getInstance().setConfiguration();
    }

    private void registerActivityLifecycle() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            }

            @Override
            public void onActivityStarted(Activity activity) {
            }

            @Override
            public void onActivityResumed(Activity activity) {
                MultiLanguageUtil.getInstance().setConfiguration();
            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
            }
        });
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }
}
